<!-- 染化料检验项目定义 -->
<template>
   <PageTabelLayout>
       <template #pageHeader>
            <div>
                <div class="search-form divClass" v-if="headerShow">
                <a-form size="small" :model="formQuery" layout="inline">
                    <a-form-item label="检验项目">
                        <a-input :style="{ width: '200px' }" class="bacClass" @press-enter="selectHandler" v-model="formQuery.checkoutProject" allow-clear />
                    </a-form-item>
                </a-form>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
                <div class="my-tool-bar divClass" style="display: flex; justify-content: flex-end;">
                    <Toolbar
                    :items="['查询', '新增', '删除']"
                    @add="addHandler"
                    @del="delHandler" 
                    @select="selectHandler" /> 
                </div> 
            </div> 
        </template>
        <template #pageTabel>
               <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" 
             style="height:100%" class='ag-theme-alpine'
             :defaultColDef="defaultColDef" :rowData="table.dataList" 
             :columnDefs="cfsValue" :localeText="localeTextData" :suppressRowClickSelection="true"/>
        </template>
        <paginationCopys :total="total" show-total show-jumper 
            show-page-size @change="changePage"
            @page-size-change="changeSize" 
            style="justify-content: center" 
            :page-size="pagination.pageSize"
            :current="pagination.page" />
        <a-drawer
          :drawer-style="{ zIndex: 9999 }"
          :mask-closable="false"
          :width="400"
          :visible="pageData.showAdd"
          unmountOnClose
          @ok="sideOk"
          @cancel="pageData.showAdd = false" 
          cancel-text="关闭"
          ok-text="保存"
          :ok-loading="saveLoading"
           >
          <template #title>
            {{ pageData.sideTitle }}
          </template>
          <div>
            <a-form ref="formRef" :model="dataForm" layout="horizontal" >
              <a-form-item
                label="检验项目"
                :label-col-flex="pageData.labelColFlex"
                field="checkoutProject"
                :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '检验项目必填' }]" >
                <a-input
                  class="bacClass"
                  v-model="dataForm.checkoutProject" 
                  @blur="dataForm.checkoutProject = dataForm.checkoutProject?.toUpperCase()"/>
              </a-form-item>
              <a-form-item
                label="指标最小值"
                :label-col-flex="pageData.labelColFlex"
                field="indexMin"
                :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '指标最小值必填' }]" > 
                <a-input-number
                  v-model="dataForm.indexMin"
                  class="bacClass"
                  :step="0.01"
                  :min="0"
                  :precision="2"
                /> 
              </a-form-item>
              <a-form-item
                label="指标最大值"
                :label-col-flex="pageData.labelColFlex"
                field="indexMax"
                :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '指标最大值必填' }]" >
                <a-input-number
                  v-model="dataForm.indexMax"
                  class="bacClass"
                  :step="0.01"
                  :min="dataForm.indexMin"
                  :precision="2" />
              </a-form-item> 
              <a-form-item label="备注" :label-col-flex="pageData.labelColFlex" field="remark">  
                <a-textarea  v-model="dataForm.remark" class="bacClass"  :max-length="{length:400}" allow-clear  show-word-limit />
              </a-form-item>
            </a-form>
          </div>
        </a-drawer>     
   </PageTabelLayout>
 
</template>

<script lang="ts">
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import { ref, reactive,onMounted } from 'vue'
import { dysuff } from '@/api/laboratory/index'
import vaildate from '@/hooks/useValidate'
import { FormInstance, Message, Modal } from '@arco-design/web-vue'
import { Dystuff } from '@/interface/basicDataInterface'
import PageTabelLayout from '@/components/pageTabelLayout.vue'

import { localeText } from '@/api/aggridZw'
import emitter from "@/hooks/useEventBus";
export default {
    name: "DystuffProjectDifin",
    setup() {
        //隐藏显示头部
        const headerShow = ref<boolean>(true)
        //抽屉保存按钮加载状态
        const saveLoading=ref<boolean>(false)
        const addHandler = () => {
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                } else if (key == "serial") {
                    dataForm[key] = 0;
                } else {
                    dataForm[key] = "";
                }
            }
            pageData.showAdd = true;
            pageData.sideTitle = "新增染化料检验项目定义";
        };
        const dysuffApi = dysuff();
        const delHandler = () => {
            let vals = gridOption.value.getSelectedRows().map((v:any) => { return v.id });
            if (vals.length > 0) {
                // let ids = vals.map((v:any) => { return v.id });
                Modal.confirm({
                    title: "提示",
                    content: "确定要批量删除选中数据吗？",
                    cancelText: "取消",
                    okText: "删除",
                    onOk: async () => {
                        await dysuffApi.batchDelDysuff([...vals]).then((res) => {
                            if (res.code === 200) {
                                Message.success("数据删除成功");
                                pagination.page = 1
                                doRefresh();
                            }  else {
                                Message.success("数据删除成功");
                            }
                        });
                    }, 
                });
            } else {
                Message.info("请选择需要删除的数据");
            }
        };
        const selectHandler = () => {
            pagination.page = 1;
            doRefresh();
        };
        const editHandler = (record: Dystuff) => {
            pageData.showAdd = true;
            pageData.sideTitle = "编辑染化料检验项目定义";
            for (var key in record) {
                dataForm[key] = record[key];
            }
        };
        const formRef = ref<FormInstance>();
        const sideOk = () => {
            saveLoading.value=true
            formRef.value?.validate().then(async (err) => {
                if (!err) {
                    if (dataForm.id) {
                      try { 
                        const res=  await dysuffApi.editDysuff([{ ...dataForm }]) 
                        if(res.code==200){
                            formRef.value?.resetFields();
                            pageData.showAdd = false;
                            saveLoading.value=false
                            Message.success({
                                content: res.message,
                                duration: 5000,
                            });
                            doRefresh();
                        } else {
                            saveLoading.value=false
                            Message.error({
                                content: res.message,
                                duration: 5000,
                            });
                        } 
                      } catch (error) {
                        saveLoading.value=false
                        console.log(error);
                        
                      }
                    }
                    else {
                 try {
                    const res=  await dysuffApi.addDysuff([{ ...dataForm }])
                      if(res.code==200){
                            formRef.value?.resetFields();
                            pageData.showAdd = false;
                            saveLoading.value=false
                            Message.success({
                                content: res.message,
                                duration: 5000,
                            });
                            doRefresh();
                        } else {
                            saveLoading.value=false
                            Message.error({
                                content: res.message,
                                duration: 5000,
                            });
                        } 
                 } catch (error) {
                    saveLoading.value=false
                    console.log(error);
                 }
                    }
                    // dysuffApi;
                }
                else {
                    saveLoading.value=false
                    console.log(err);
                }
            });
        };
        const onTimeOk = (dataString: string) => {
            dataForm.createTime = dataString;
        };
        const scrollbar = ref(true);
        const { selectedRowKeys } = useRowSelection();
        async function doRefresh() {
        try {
            pageData.pageLoading = true;
           const res= await dysuffApi.getPageQueryDysuffList({
                page: pagination.page,
                size: pagination.pageSize,
                deleteState: 0,
                checkoutProject: formQuery.checkoutProject
            })
                if (res.code === 200) {
                    gridOption.value.sizeColumnsToFit();
                    table.handleSuccess(res.data.list);
                    gridOption.value.setRowData(res.data.list);
                    total.value = res.data.total;
                }else {
                    Message.error({
                        content:res.message,
                        duration: 5000,
                    })
                }
        } catch (error) {
            console.log(error);    
        }finally{
            pageData.pageLoading = false;
        }
               
        }
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const formQuery=reactive<any>({
            checkoutProject:''
        })
        const pageData = reactive<{
            dystuffList: Dystuff[];
            showAdd: boolean;
            sideTitle: string;
            dropDownData: any;
            pageLoading: boolean;
            theight: number;
            tablediv: any;
            rHeight: number | undefined;
            labelColFlex: string;
        }>({
            dystuffList: [],
            showAdd: false,
            sideTitle: "新增染化料检验项目定义",
            dropDownData: "",
            pageLoading: false,
            theight: 0,
            tablediv: null,
            rHeight: 0,
            labelColFlex: '100px'
        });
        const dataForm = reactive<Dystuff>({
            id: null,
            serial: 0,
            createTime: "",
            checkoutProject: "",
            indexMin: 0.01,
            indexMax: 0.01,
            createName: "",
            remark: "",
        });
        //检验表单是否含有中文的方法
        const hasChiese = vaildate.includeChinese;
        const tableColumns = useTableColumn([
            {
                title: "序号",
                key: "serial",
                dataIndex: "serial",
                width: 150,
            },
            {
                title: "检验项目",
                key: "checkoutProject",
                dataIndex: "checkoutProject",
                width: 150,
            },
            {
                title: "指标最小值",
                key: "indexMin",
                dataIndex: "indexMin",
                width: 150,
            },
            {
                title: "指标最大值",
                key: "indexMax",
                dataIndex: "indexMax",
                width: 150,
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150,
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150,
            },
            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 150,
            },
            {
                title: "最后修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150,
            },
            {
                title: "最后修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 150,
            },
            {
                title: "操作",
                key: "id",
                dataIndex: "id",
                slotName: "action",
                width: 150,
                fixed: "right",
            },
        ]);
        onMounted(() => {
            // 第一个页面需要在刚进入就调用一次  切换tap时也需要调用
            doRefresh();
            emitter.on("refresh-DystuffProjectDifin", () => {
                doRefresh();
                gridOption.value.sizeColumnsToFit();
            });
        });
        //表格方面
        const gridOption = ref();
        const gridReady = (params:any) => {
          gridOption.value = params.api;
          //调整表格自适应大小
          gridOption.value.sizeColumnsToFit(); 
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            flex: 1
        }
        let cfsValue:any[] = tableColumns.map(o => {
          let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            if (o.slotName === 'action') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj["width"] = 80
                obj['cellRenderer'] = {
                    template: `<a-tag color="#ff7d00" @click="a" class="gesture">修改</a-tag>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        return {
                            a
                        }
                    }

                }
            }

            return obj
        });
        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        cfsValue = a.concat(cfsValue);
        const total = ref(10);
        const changePage = (val:any) => {
            pagination.page = val
            doRefresh();
        }
        const changeSize = (val:any) => {
            pagination.pageSize = val
            doRefresh();
        }

        const localeTextData :any = ref(localeText);
        
        return {
            headerShow,
            formQuery,
            saveLoading,
            localeTextData,
            addHandler, 
            delHandler,
            selectHandler,
            pagination,
            table,
            rowKey,
            selectedRowKeys,
            tableColumns,
            scrollbar,
            editHandler,
            pageData,
            sideOk,
            dataForm,
            onTimeOk,
            formRef,
            hasChiese,
            gridReady,
            defaultColDef,
            cfsValue,
            total,
            changePage,
            changeSize
        };
    },
    components: { PageTabelLayout, }
}
</script>

<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.arco-textarea-wrapper){
    background: #fff;
    border: 1px solid #c9cdd3;
    width: 270px 
}

.aInput{
  width: 270px;background: #fff;border: 1px solid #c9cdd3;
}
</style>